package com.zhi.inisyccalllog.services;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;

import androidx.core.content.ContextCompat;

import android.util.Log;

import com.google.gson.Gson;
import com.zhi.inisyccalllog.ASCallLogManager;
import com.zhi.inisyccalllog.beans.ASCallLogInfoBean;
import com.zhi.inisyccalllog.beans.ASCallLogTime;
import com.zhi.inisyccalllog.logger.ASLogger;
import com.zhi.inisyccalllog.util.ASUtil;

import java.util.ArrayList;

public class ASCallLogInfo {

    @SuppressLint("Recycle")
    public static ArrayList<ASCallLogInfoBean> getList(Context paramContext) {
        ArrayList<ASCallLogInfoBean> arrayList = new ArrayList<>();
        try {
            ContentResolver mContentResolver = paramContext.getContentResolver();
            if (mContentResolver == null) {
                return arrayList;
            }

            if (ContextCompat.checkSelfPermission(paramContext, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                return arrayList;
            }

            Uri mCallUri = CallLog.Calls.CONTENT_URI;
            if (mCallUri == null) {
                return arrayList;
            }

            String[] mColumns = {
                    CallLog.Calls.IS_READ,              //用户是否已阅读或操作，与{@link #NEW}字段不同，该字段要求用户确认条目的存在，这意味着用户已经与条目进行了交互。
                    CallLog.Calls.NEW,                  //呼叫是否被确认
                    CallLog.Calls.CACHED_NUMBER_TYPE,   //电话类型，home work
                    CallLog.Calls.CACHED_NAME,          // 通话记录的联系人
                    CallLog.Calls.NUMBER,               // 通话记录的电话号码
                    CallLog.Calls.DATE,                 // 通话记录的日期
                    CallLog.Calls.DURATION,             // 通话时长
                    CallLog.Calls.TYPE,                 // 通话类型
            };

            long dStartTime = ASUtil.getStartTime();
            long dEndTime = ASUtil.getEndTime();
            String gsql = "date>=" + dStartTime + " AND date<=" + dEndTime + " AND type=2";
//            String gsql = "date DESC limit 1000";
            Log.d(ASCallLogManager.class.getSimpleName(), "gsql: " + gsql);

            Cursor cursor = mContentResolver.query(
                    mCallUri,
                    mColumns,
                    gsql,
                    null,
                    CallLog.Calls.DEFAULT_SORT_ORDER
            );

            if (cursor == null) {
                return arrayList;
            }

            while (cursor.moveToNext()) {
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                String typeString = "";
                switch (type) {
                    case CallLog.Calls.INCOMING_TYPE: {
                        //"1-打入"
                        typeString = "INCOMING_TYPE";
                        break;
                    }
                    case CallLog.Calls.OUTGOING_TYPE: {
                        //"2-打出"
                        typeString = "OUTGOING_TYPE";
                        break;
                    }
                    case CallLog.Calls.MISSED_TYPE: {
                        //"3-未接"
                        typeString = "MISSED_TYPE";
                        break;
                    }
                    case CallLog.Calls.VOICEMAIL_TYPE: {
                        //"4-语音信箱"
                        typeString = "VOICEMAIL_TYPE";
                        break;
                    }
                    case CallLog.Calls.REJECTED_TYPE: {
                        //"5-拒接"
                        typeString = "REJECTED_TYPE";
                        break;
                    }
                    case CallLog.Calls.BLOCKED_TYPE: {
                        //"6-自动阻止的呼叫,拉黑"
                        typeString = "BLOCKED_TYPE";
                        break;
                    }
                    default:
                        break;
                }

                //只查拨出的记录
                if (CallLog.Calls.OUTGOING_TYPE != type) {
                    continue;
                }

                int isRead = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.IS_READ));
                int isNew = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.NEW));
                String numberType = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE));

                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                String mobile = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));

                long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                //String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
                //String time = new SimpleDateFormat("HH:mm").format(new Date(dateLong));

                //String dayCurrent = new SimpleDateFormat("dd").format(new Date());
                //String dayRecord = new SimpleDateFormat("dd").format(new Date(dateLong));

                ASCallLogInfoBean callLogInfoBean = new ASCallLogInfoBean();
                callLogInfoBean.setIsNew(String.valueOf(isNew));
                callLogInfoBean.setIsRead(isRead == 0 ? "YES" : "NO");
                callLogInfoBean.setDateLong(String.valueOf(dateLong));
                callLogInfoBean.setDuration(String.valueOf(duration));
                callLogInfoBean.setName(name);
                callLogInfoBean.setMobile(mobile);
                callLogInfoBean.setType(String.valueOf(type));
                callLogInfoBean.setTypeDes(typeString);
                arrayList.add(callLogInfoBean);

                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "getLogList: name: " + name + ", mobile: " + mobile + ", duration: " + duration + ", type: " + type + ", typeString: " + typeString + ", dateLong: " + dateLong);
//                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "getLogList: isRead: " + isRead + ", isNew: " + isNew);
//                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "---------------------");
            }

            if (!cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    @SuppressLint("Recycle")
    public static ArrayList<ASCallLogInfoBean> getLast10MinCallList(Context paramContext) {
        ArrayList<ASCallLogInfoBean> arrayList = new ArrayList<>();
        try {
            ContentResolver mContentResolver = paramContext.getContentResolver();
            if (mContentResolver == null) {
                return arrayList;
            }

            if (ContextCompat.checkSelfPermission(paramContext, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                return arrayList;
            }

            Uri mCallUri = CallLog.Calls.CONTENT_URI;
            if (mCallUri == null) {
                return arrayList;
            }

            String[] mColumns = {
                    CallLog.Calls.IS_READ,              //用户是否已阅读或操作，与{@link #NEW}字段不同，该字段要求用户确认条目的存在，这意味着用户已经与条目进行了交互。
                    CallLog.Calls.NEW,                  //呼叫是否被确认
                    CallLog.Calls.CACHED_NUMBER_TYPE,   //电话类型，home work
                    CallLog.Calls.CACHED_NAME,          // 通话记录的联系人
                    CallLog.Calls.NUMBER,               // 通话记录的电话号码
                    CallLog.Calls.DATE,                 // 通话记录的日期
                    CallLog.Calls.DURATION,             // 通话时长
                    CallLog.Calls.TYPE,                 // 通话类型
            };

            ASCallLogTime asCallLogTime = ASUtil.getCurDateTime();
            long dStartTime = asCallLogTime.getStartTime();
            long dEndTime = asCallLogTime.getEndTime();
            String gsql = "date>=" + dStartTime + " AND date<=" + dEndTime;
//            String gsql = "date>=" + dStartTime + " AND date<=" + dEndTime + " AND type=2";
//            String gsql = "date DESC limit 1000";
            Log.d(ASCallLogManager.class.getSimpleName(), "gsql: " + gsql);

            Cursor cursor = mContentResolver.query(
                    mCallUri,
                    mColumns,
                    gsql,
                    null,
                    CallLog.Calls.DEFAULT_SORT_ORDER
            );

            if (cursor == null) {
                return arrayList;
            }

            while (cursor.moveToNext()) {
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                String typeString = "";
                switch (type) {
                    case CallLog.Calls.INCOMING_TYPE: {
                        //"1-打入"
                        typeString = "INCOMING_TYPE";
                        break;
                    }
                    case CallLog.Calls.OUTGOING_TYPE: {
                        //"2-打出"
                        typeString = "OUTGOING_TYPE";
                        break;
                    }
                    case CallLog.Calls.MISSED_TYPE: {
                        //"3-未接"
                        typeString = "MISSED_TYPE";
                        break;
                    }
                    case CallLog.Calls.VOICEMAIL_TYPE: {
                        //"4-语音信箱"
                        typeString = "VOICEMAIL_TYPE";
                        break;
                    }
                    case CallLog.Calls.REJECTED_TYPE: {
                        //"5-拒接"
                        typeString = "REJECTED_TYPE";
                        break;
                    }
                    case CallLog.Calls.BLOCKED_TYPE: {
                        //"6-自动阻止的呼叫,拉黑"
                        typeString = "BLOCKED_TYPE";
                        break;
                    }
                    default:
                        break;
                }

//                if (CallLog.Calls.OUTGOING_TYPE != type) {
//                    continue;
//                }

                int isRead = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.IS_READ));
                int isNew = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.NEW));
                String numberType = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE));

                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                String mobile = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));

                long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                //String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
                //String time = new SimpleDateFormat("HH:mm").format(new Date(dateLong));

                //String dayCurrent = new SimpleDateFormat("dd").format(new Date());
                //String dayRecord = new SimpleDateFormat("dd").format(new Date(dateLong));

                ASCallLogInfoBean callLogInfoBean = new ASCallLogInfoBean();
                callLogInfoBean.setIsNew(String.valueOf(isNew));
                callLogInfoBean.setIsRead(isRead == 0 ? "YES" : "NO");
                callLogInfoBean.setDateLong(String.valueOf(dateLong));
                callLogInfoBean.setDuration(String.valueOf(duration));
                callLogInfoBean.setName(name);
                callLogInfoBean.setMobile(mobile);
                callLogInfoBean.setType(String.valueOf(type));
                callLogInfoBean.setTypeDes(typeString);
                arrayList.add(callLogInfoBean);

                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "getLogList: name: " + name + ", mobile: " + mobile + ", duration: " + duration + ", type: " + type + ", typeString: " + typeString + ", dateLong: " + dateLong);
//                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "getLogList: isRead: " + isRead + ", isNew: " + isNew);
//                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "---------------------");
            }

            if (!cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    public static String getListZipString(Context paramContext) {
        String zipString = "";
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                ArrayList<ASCallLogInfoBean> infoBeans = getList(paramContext);
                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "call log count: " + infoBeans.size());
                String result = new Gson().toJson(infoBeans).trim();
                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "call log ori size: " + result.length());

                zipString = ASUtil.stringToGZIP(result);
                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "call log zip size: " + zipString.length());

                infoBeans.clear();
                infoBeans = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return zipString;
    }
}
